package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
)

func main() {
	// 客户端访问: http://127.0.0.1:8000/add?a=1&b=2
	// 返回的格式化: json {"data": 3}
	// 1. callID的问题: r.URL.Path 2. 数据的传输协议 http的参数传递协议 4. 网络传输协议 http
	http.HandleFunc("/add", func(w http.ResponseWriter, r *http.Request) {
		err := r.ParseForm() // 解析参数
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println("path: ", r.URL.Path)

		a, err := strconv.Atoi(r.Form["a"][0])
		if err != nil {
			fmt.Println(err)
			return
		}
		b, err := strconv.Atoi(r.Form["b"][0])
		if err != nil {
			fmt.Println(err)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		jData, err := json.Marshal(map[string]int{
			"data": a + b,
		})
		if err != nil {
			fmt.Println(err)
			return
		}

		num, err := w.Write(jData)
		if err != nil {
			fmt.Println(num, err)
			return
		}
	})

	err := http.ListenAndServe(":8000", nil)
	if err != nil {
		fmt.Println(err)
	}
}
